use io::BufReader as Reader;
use std::collections::HashMap;
use std::fs::File;
use std::io::{self, BufRead};

pub fn converter(input: &str, tp: &str) -> String {
    // the map of phrase
    let t2s = load_map("t2s.txt").unwrap();
    let s2t = load_map("s2t.txt").unwrap();
    let res = match tp {
        "s2t" => {
            let input = input.to_string();
            let res = s2t.get(&input).unwrap_or(&input);
            res.to_string()
        }
        "t2s" => {
            let input = input.to_string();
            let res = t2s.get(&input).unwrap_or(&input);
            res.to_string()
        }
        _ => input.to_string(),
    };
    res
}

// The map is too long, so I truncated it.
// You can find the full version in 
// s2t: https://github.com/houbb/opencc4j/blob/master/src/main/resources/data/dictionary/STPhrases.txt
// t2s: https://github.com/houbb/opencc4j/blob/master/src/main/resources/data/dictionary/TSPhrases.txt
fn load_map(path: &str) -> io::Result<HashMap<String, String>> {
    let mut map = HashMap::<String, String>::new();
    let file = File::open(path)?;
    let reader = Reader::new(file);

    for line in reader.lines() {
        let line = line?;
        let line = line.split_whitespace().collect::<Vec<&str>>();
        let t = line[0];
        let s = line[1];
        map.insert(t.to_string(), s.to_string());
    }
    Ok(map)
}
